package com.murphy.algorithm.likou;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * k大的数
 * 1、定义优先队列容量k（最小顶）
 *
 * 也可以自己定义一个数组容量k
 * 排序，每次对比第一个如果小丢弃，如果大把第一个替换重新排序
 * @author dongsufeng
 * @version 4.0
 * @date 2023/2/22 14:36
 */
public class KBigData {

    public int k1(int k , int[] nums){

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k);
        for (int i = 0; i < nums.length; i++) {
            if (priorityQueue.size()<k){
                priorityQueue.offer(nums[i]);
            }else if (priorityQueue.peek()<nums[i]){
                priorityQueue.poll();
                priorityQueue.offer(nums[i]);
            }
        }
        return priorityQueue.peek();
    }
    public int k(int k , int[] nums){
        PriorityQueue<Integer> queue = new PriorityQueue(k);
        for (int i = 0; i < nums.length; i++) {
            if (queue.size() < k){
                queue.offer(nums[i]);
            }else {
                int top = queue.peek();
                if (top < nums[i]){
                    queue.poll();
                    queue.offer(nums[i]);
                }
            }
        }
        return queue.peek();
    }

    public static void main(String[] args) {
        int[] nums={1,4,2,4,5,6,7};
        KBigData kBigData = new KBigData();
        System.out.println(kBigData.k(3,nums));
    }
}
